13/04/2022

This Demo

Beginning with RStudio and git

RStudio hints

  • Always work in an R project
  • Use a git repo for collaboration
  • Do not setwd()
  • Do not save workspace to .Rdata
  • Use Control+Shift+F10 often

Markdown versus R script

  • Code is the same
  • RMarkdown adds formatted text and outputs
  • RMarkdown can produce output in html, pdf, and slides
  • Perfect for reports and … demos

Where to get R packages

Installing packages

# Install some standard spatial packages from CRAN
if (!require("sf", quietly = TRUE))
  install.packages("sf")
if (!require("terra", quietly = TRUE))
  install.packages("terra")

# package from Bioconductor
if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")
BiocManager::install()
BiocManager::install("EBImage")

Installing from github

# Install development package from github
if (!require("remotes", quietly = TRUE))
  install.packages("remotes")

if (!require("ReLTER", quietly = TRUE))
  remotes::install_github("ropensci/ReLTER")

Loading packages

After installing, we need to load the packages into this R session.

# Convenient way to load list of packages
pkg_list <- c("sf", "terra", "ReLTER", "tmap")
lapply(pkg_list, require, character.only = TRUE)
## [[1]]
## [1] TRUE
## 
## [[2]]
## [1] TRUE
## 
## [[3]]
## [1] TRUE
## 
## [[4]]
## [1] TRUE

R Spatial

An initial example

Use the geodata package for sample data. Get administrative boundaries (from GADM) and monthly precipitation rasters (from WorldClim) for Slovakia.

remotes::install_github("rspatial/geodata")
## 
## ── R CMD build ─────────────────────────────────────────────────────────────────
##   
   checking for file ‘/tmp/RtmpHtkREj/remotes154641f50948f/rspatial-geodata-ee97863/DESCRIPTION’ ...
  
✔  checking for file ‘/tmp/RtmpHtkREj/remotes154641f50948f/rspatial-geodata-ee97863/DESCRIPTION’
## 
  
─  preparing ‘geodata’:
## 
  
   checking DESCRIPTION meta-information ...
  
✔  checking DESCRIPTION meta-information
## 
  
─  installing the package to process help pages
## 
  
─  saving partial Rd database (8.2s)
## 
  
─  checking for LF line-endings in source and make files and shell scripts
## 
  
─  checking for empty or unneeded directories
## 
  
─  building ‘geodata_0.5-4.tar.gz’
## 
  
   
## 
library(geodata)
slv <- gadm("Slovakia", level=2, path=tempdir())
# Convert to `sf` class for plotting
slv <- st_as_sf(slv)
slv_precip <- worldclim_country("Slovakia",
                                var = "prec", path = tempdir())

Display the data with tmap, and use OpenStreetMaps as background.

tmap_mode("view")
tm_basemap("OpenStreetMap.Mapnik") +
  tm_shape(slv) + tm_borders(col = "purple", lwd = 2) +
  tm_shape(slv_precip$SVK_wc2.1_30s_prec_1) + 
  tm_raster(palette = "YlGnBu", alpha=0.7)

Now a different month

tm_basemap("OpenStreetMap.Mapnik") +
  tm_shape(slv) + tm_borders(col = "purple", lwd = 2) +
  tm_shape(slv_precip$SVK_wc2.1_30s_prec_8) +
  tm_raster(palette = "YlGnBu", alpha=0.7)